package com.whiteblue.model;

import com.jfinal.plugin.ehcache.CacheKit;
import com.whiteblue.tool.Model;
import com.whiteblue.tool.SecurityUtil;

/**
 * Created by WhiteBlue on 15/4/4.
 */
public class User extends Model<User> {

    public static final User dao = new User();

    private static final String USER_CACHE = "user";

    public User() {
        super(USER_CACHE);
    }


    public User getById(int id){
        return loadModel(id);
    }

    public void register(String email, String password, String name) {
        this.set("email", email).set("password", SecurityUtil.strToMD5(password)).set("name", name);
        this.save();
    }

    public void editInfo(String feeling,String location){
        this.set("feeling",feeling).set("location",location);
        this.update();
        removeCache();
    }

    public User login(String email, String password) {
        User user = dao.findFirst("select id from b_user where email = ? and password = ?", email, SecurityUtil.strToMD5(password));
        if (user == null) {
            return null;
        } else {
            return loadModel(user.getInt("id"));
        }
    }

    public User loginByCookies(String email, String password_md5) {
        User user = dao.findFirst("select id from b_user where email = ? and password = ?", email, password_md5);
        if (user == null) {
            return null;
        } else {
            return loadModel(user.getInt("id"));
        }
    }

    public boolean find(String email, String name) {
        User user = dao.findFirst("select id from b_user where email = ? or name = ?", email, name);
        if (user == null) {
            return false;
        } else {
            return true;
        }
    }

    public void removeCache(){
        CacheKit.removeAll(USER_CACHE);
    }


}
